<?php
namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\IndexRequest;
use App\Http\Requests\NeighborHelpCreateRequest;
use App\Http\Requests\NeighborInfoRequest;
use App\Libraries\msg\Push;
use App\Mail\Basic;
use App\Models\Banner;
use App\Models\ClientUserHouse;
use App\Models\ClientUserMessage;
use App\Models\HouseDistrict;
use App\Models\NeighborHelp;
use App\Models\NeighborHelpCommend;
use App\Models\NeighborHelpComment;
use App\Models\NeighborInfo;
use App\Models\NeighborInfoType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NeighborController extends CommonController {
	
	/**
	 * 获取可发布的类别
	 */
	public function type(){
		$data = NeighborHelp::$type;
		return json_success('OK',$data);
	}
	
	/**
	 * @return array
	 * 查看邻里分享列表
	 */
	public function share(BasicRequest $request){
		$this->check_login();
		$keyword = $request->input('keyword');
		// 根据用户的主房屋来确定显示哪个小区的生活信息
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;
		$data = NeighborHelp::where(['house_id'=>$house_id])->share($keyword)->pagesParse();
		return json_success('OK',$data);
	}
	
	// 我的分享列表
	public function share_mine(){
		$data = NeighborHelp::where(['uid'=>$this->uid])->share()->pagesParse();
		return json_success('OK',$data);
	}
	
	// 我要分享
	public function share_create(NeighborHelpCreateRequest $request){
		$this->check_login();
		$title = $request->input('title');
		$description = $request->input('description');
		$images = json_decode($request->input('images'),true);
		$comment_allow = $request->input('comment_allow',1);
		
		$help_id = NeighborHelp::shareCreate($this->uid,$title,$description,$images,$comment_allow);
		$return = [
			'id'	=> $help_id,
		];
		return json_return($help_id,'','发布成功',$return);
	}
	
	/**
	 * 查看租车信息列表，分页
	 */
	public function carpool(BasicRequest $request){
		$this->check_login();
		$keyword = $request->input('keyword');
		// 根据用户的主房屋来确定显示哪个小区的生活信息
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;
		
		$data = NeighborHelp::where(['house_id'=>$house_id])->carpool($keyword)->pagesParse();
		return json_success('OK',$data);
	}
	
	// 发布租车信息
	public function carpool_create(NeighborHelpCreateRequest $request){
		$this->check_login();
		$title = $request->input('title');
		$description = $request->input('description');
		$images = json_decode($request->input('images'),true);
		$comment_allow = $request->input('comment_allow',1);
		
		$help_id = NeighborHelp::carpoolCreate($this->uid,$title,$description,$images,$comment_allow);
		$return = [
			'id'	=> $help_id,
		];
		return json_return($help_id,'','发布成功',$return);
	}
	
	/**
	 * 查看租房信息列表，分页
	 */
	public function renting(BasicRequest $request){
		$this->check_login();
		$keyword = $request->input('keyword');
		// 根据用户的主房屋来确定显示哪个小区的生活信息
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;
		$data = NeighborHelp::where(['house_id'=>$house_id])->renting($keyword)->pagesParse();
		return json_success('OK',$data);
	}
	
	// 发布租房信息
	public function renting_create(NeighborHelpCreateRequest $request){
		$this->check_login();
		$title = $request->input('title');
		$description = $request->input('description');
		$images = json_decode($request->input('images'),true);
		$comment_allow = $request->input('comment_allow',1);
		
		$help_id = NeighborHelp::rentingCreate($this->uid,$title,$description,$images,$comment_allow);
		$return = [
			'id'	=> $help_id,
		];
		return json_return($help_id,'','发布成功',$return);
	}
	
	/**
	 * 查看二手买卖信息列表，分页
	 */
	public function oldstuff(BasicRequest $request){
		$this->check_login();
		$keyword = $request->input('keyword');
		// 根据用户的主房屋来确定显示哪个小区的生活信息
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;
		$data = NeighborHelp::where(['house_id'=>$house_id])->oldstuff($keyword)->pagesParse();
		return json_success('OK',$data);
	}
	
	// 发布二手买卖信息
	public function oldstuff_create(NeighborHelpCreateRequest $request){
		$this->check_login();
		$title = $request->input('title');
		$description = $request->input('description');
		$images = json_decode($request->input('images'),true);
		$comment_allow = $request->input('comment_allow',1);
		
		$help_id = NeighborHelp::oldstuffCreate($this->uid,$title,$description,$images,$comment_allow);
		$return = [
			'id'	=> $help_id,
		];
		return json_return($help_id,'','发布成功',$return);
	}
	
	/**
	 * @return array
	 * 查看社区活动
	 */
	public function activity(BasicRequest $request){
		$this->check_login();
		$keyword = $request->input('keyword');
		// 根据用户的主房屋来确定显示哪个小区的生活信息
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;
		$data = NeighborHelp::where(['house_id'=>$house_id])->activity($keyword)->pagesParse();
		return json_success('OK',$data);
	}
	
	// 活动添加
	public function activity_create(NeighborHelpCreateRequest $request){
		$this->check_login();
		$title = $request->input('title');
		$description = $request->input('description');
		$images = json_decode($request->input('images'), true);
		$comment_allow = $request->input('comment_allow', 1);

		$help_id = NeighborHelp::helpCreate($this->uid,$title, $description, $images, $comment_allow);
		$return = [
			'id' => $help_id,
		];
		return json_return($help_id,'','发布成功',$return);
	}
	
	/**
	 * @return array
	 * 查看其他分享
	 */
	public function other(BasicRequest $request){
		$this->check_login();
		$keyword = $request->input('keyword');
		// 根据用户的主房屋来确定显示哪个小区的生活信息
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;
		$data = NeighborHelp::where(['house_id'=>$house_id])->other($keyword)->pagesParse();
		return json_success('OK',$data);
	}
	
	// 活动添加
	public function other_create(NeighborHelpCreateRequest $request)
	{
		$this->check_login();
		$title = $request->input('title');
		$description = $request->input('description');
		$images = json_decode($request->input('images'), true);
		$comment_allow = $request->input('comment_allow', 1);
		
		$help_id = NeighborHelp::otherCreate($this->uid,$title, $description, $images, $comment_allow);
		$return = [
			'id' => $help_id,
		];
		return json_return($help_id,'','发布成功',$return);
	}
	
	/**
	 * 邻里互助，二手与租车信息单页列表
	 */
	public function help_mutual(BasicRequest $request){
		// 根据用户的主房屋来确定显示哪个小区的生活信息
        $this->check_login();
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;

		$return = [
			'carpool'	=> NeighborHelp::where(['house_id'=>$house_id])->carpool()->pagesParse()->take(4),
			'oldstuff'	=> NeighborHelp::where(['house_id'=>$house_id])->renting()->pagesParse()->take(4),
		];
		return json_success('OK',$return);
	}
	
	
	/**
	 * @param NeighborHelpCreateRequest $request
	 * @throws ApiException
	 * @return array
	 * 信息发布总接口，
	 */
	public function help_create(NeighborHelpCreateRequest $request)
	{
		$this->check_login();
		$type = $request->input('type');
		$title = $request->input('title');
		$description = $request->input('description');
		$images = json_decode($request->input('images'), true);
		$comment_allow = $request->input('comment_allow', 1);
		$help_type = NeighborHelp::$type;
		$types = array_pluck($help_type,'type');
		if(!array_keys($types,$type)){
			throw new ApiException('所选信息类型不存在');
		}
		if($type==3 && empty($images)){
			throw new ApiException('请上传图片');
		}
		$help_id = NeighborHelp::helpCreate($this->uid, $title,$description, $images, $type,$comment_allow);
		$return = [
			'id' => $help_id,
		];
		return json_return($help_id,'','发布成功',$return);
	}
	
	/**
	 * @param Request $request
	 * @return array
	 * 邻里圈帮助详情
	 */
	public function help_detail(Request $request){
		$id = $request->input('help_id');
		$help = NeighborHelp::list()->where(['neighbor_help.id'=>$id])->pagesParse()->first();
		return json_success('OK',$help);
	}
	
	/**
	 * @param Request $request
	 * @return array
	 * 邻里圈帮助评论列表，分页
	 */
	public function help_comment_list(Request $request){
		$help_id = $request->input('help_id');
		$data = NeighborHelpComment::where(['help_id'=>$help_id])->pages();
		return json_success('OK',$data);
	}
	
	/**
	 * @param Request $request
	 * @throws ApiException
	 * @return array
	 * 邻里圈添加评论
	 */
	public function help_comment_create(Request $request){
		$this->check_login();
		\Validator::make($request->all(),[
			'help_id'	=> 'bail|required|numeric',
			'comment'	=> 'bail|required',
		],[
			'help_id.required'	=> '内容ID必传',
			'help_id.numeric'	=> '内容ID格式错误',
			'comment.required'	=> '请输入评论内容',
		])->validate();
		$help_id = $request->input('help_id');
		$comment = $request->input('comment');
		$help = NeighborHelp::find($help_id);
		// 是否允许评论
		if($help->comment_allow == 0){
			throw new ApiException('该信息已设置为不允许评论');
		}
		$add = [
			'help_id'	=> $help_id,
			'uid'		=> $this->uid,
			'comment'	=> $comment,
			'status'	=> 1,
		];
		$id = NeighborHelpComment::create($add)->id;
		// 同时总评论数量加1
		NeighborHelp::where(['neighbor_help.id'=>$help_id])->increment('comment_count');
		$push = new Push();
		$push->queue($help->uid,'您的邻里圈收到新评论',$comment,['type'=>'neighbor_help_comment','neighbor_help_id'=>$help_id]);
		return json_return($id,'','评论成功',['id'=>$id]);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 邻里圈文章点赞，如果存在则取消赞，可一直重复
	 */
	public function help_commend_create(BasicRequest $request){
		$this->check_login();
		\Validator::make($request->all(),[
			'help_id'	=> 'required',
		],[
			'help_id.required'	=> '信息id参数必传',
		])->validate();
		$help_id = $request->input('help_id');
		$exist = NeighborHelpCommend::where(['uid'=>$this->uid,'help_id'=>$help_id])->count();
		if($exist){
			$id = NeighborHelpCommend::where(['uid'=>$this->uid,'help_id'=>$help_id])->delete();
			// 同时总点赞数量减1
			NeighborHelp::where(['id'=>$help_id])->decrement('commend_count');
			return json_return($id,'','已取消点赞',['id'=>$id,'msg'=>'已取消点赞']);
		}else{
			$add = [
				'help_id'	=> $help_id,
				'uid'		=> $this->uid,
			];
			$id = NeighborHelpCommend::create($add)->id;
			// 同时总点赞数量加1
			NeighborHelp::where(['id'=>$help_id])->increment('commend_count');
			$help = NeighborHelp::find($help_id);
			$push = new Push();
			$push->queue($help->uid,'您的邻里圈收到新点赞','有用户赞了您的发布信息：'.$help->title,['type'=>'neighbor_help_commend','neighbor_help_id'=>$help_id]);
			return json_return($id,'','点赞成功',['id'=>$id,'msg'=>'点赞成功']);
		}
	}
	
	/**
	 * @param Request $request
	 * @return array
	 * 邻里圈文章撤销/删除
	 */
	public function help_delete(Request $request){
		$this->check_login();
		$help_id = $request->input('help_id');
		$var = NeighborHelp::where(['uid'=>$this->uid,'id'=>$help_id])->delete();
		return json_return($var,'','已成功删除此发布信息');
	}
	
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 便民生活信息导航
	 */
	public function info_index(BasicRequest $request){
		$this->check_login();
		// 根据用户的主房屋来确定显示哪个小区的生活信息
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;
		$banner = Banner::where(['type'=>1,'house_id'=>$house_id])->get();
		$type = NeighborInfoType::limit(4)->get();
		$return = [
			'banner'	=> $banner,
			'type'		=> $type,
			'message_unview_count'	=> group99(ClientUserMessage::where(['uid'=>$this->uid,'viewed'=>0])->count()),
		];
		return json_success('OK',$return);
	}
	
	// 便民生活信息分类
	public function info_type(BasicRequest $request){
		$this->check_login();
		$data = NeighborInfoType::get();
		return json_success('OK',$data);
	}
	
	// 某个小区下的便民生活导航
	public function info(NeighborInfoRequest $request){
		$this->check_login();
		$type_id = $request->input('type_id');
		$lat = $request->input('lat');
		$lng = $request->input('lng');
		
		// 根据用户的主房屋来确定显示哪个小区的生活信息
		$primary_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->value('house_id');
		$house_id = HouseDistrict::firstOrNew(['id'=>$primary_house])->detail()->details->first()->id;
		if(empty($house_id)){
			$house_geo = HouseDistrict::select(DB::raw('*,round(6378.138*2*asin(sqrt(pow(sin((' . $lat . '*pi()/180-lat*pi()/180)/2),2)+cos(' . $lat . '*pi()/180)*cos(lat*pi()/180)* pow(sin((' . $lng . '*pi()/180-lng*pi()/180)/2),2)))*1000) as distance'))->district()->orderBy('distance','asc')->first();
			$house_id = $house_geo->id;
		}
		$data = NeighborInfo::select(DB::raw('*,round(6378.138*2*asin(sqrt(pow(sin((' . $lat . '*pi()/180-lat*pi()/180)/2),2)+cos(' . $lat . '*pi()/180)*cos(lat*pi()/180)* pow(sin((' . $lng . '*pi()/180-lng*pi()/180)/2),2)))*1000) as distance'))->where(['house_id'=>$house_id])
			->when($type_id,function($query) use ($type_id){
			$query->where(['type_id'=>$type_id]);
		})
        ->orderBy('sort','desc')
        ->orderBy('distance','asc')
        ->orderBy('id','desc')
        ->pages()->each(function($v,$k){
            if($v->distance>1000){
                $v->distance = (round($v->distance/1000)).'千';
            }
        });
		return json_success('OK',$data);
	}
	
	public function info_detail(BasicRequest $request){
		$id = $request->input('id');
		$data = NeighborInfo::find($id);

		return json_success('OK',$data);
	}
}